package com.sc.VenusQueryBeta.ui.fragments.home.child.tabs;

import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;

import com.gongwen.marqueen.SimpleMF;
import com.gongwen.marqueen.SimpleMarqueeView;
import com.hengjun.kingstar.sdk.base.BasePresenter;
import com.hengjun.kingstar.sdk.base.fragment.BaseRecycleFragment;
import com.hengjun.kingstar.sdk.utils.LogUtil;
import com.hengjun.kingstar.sdk.utils.LogUtils;
import com.hengjun.kingstar.sdk.utils.ToastUtils;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.sc.VenusQueryBeta.R;
import com.sc.VenusQueryBeta.adapter.BannerAdapter;
import com.sc.VenusQueryBeta.adapter.home.HotActivityListAdapter;
import com.sc.VenusQueryBeta.api.Host;
import com.sc.VenusQueryBeta.constant.Constants;
import com.sc.VenusQueryBeta.contract.home.tabs.ZhiXunContract;
import com.sc.VenusQueryBeta.model.bean.home.HomeBannerBean;
import com.sc.VenusQueryBeta.model.bean.home.HomeNoticeBean;
import com.sc.VenusQueryBeta.model.bean.home.HostListBean;
import com.sc.VenusQueryBeta.presenter.home.tabs.ZhiXunPresenter;
import com.sc.VenusQueryBeta.ui.activites.details.TestDetailActivity;
import com.sc.VenusQueryBeta.ui.activites.details.ZiXunDetailsActivity;
import com.sc.VenusQueryBeta.ui.widgets.ZoomOutPageTransformer;
import com.wenld.wenldbanner.AutoTurnViewPager;
import com.wenld.wenldbanner.DefaultPageIndicator;
import com.wenld.wenldbanner.OnPageClickListener;
import com.wenld.wenldbanner.helper.UIContact;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;

/**
 * Created by SC-02 on 2018/9/19.
 * 最新资讯fragment
 */

public class ZhiXunFragment extends BaseRecycleFragment<ZhiXunContract.ZhiXunPresenter> implements ZhiXunContract.IZhihuView {

    @BindView(R.id.smv_notice)
    SimpleMarqueeView smvNotice;
//    @BindView(R.id.ptr_class)
//    PtrClassicFrameLayout ptrClass;
    @BindView(R.id.rv_consultation)
    XRecyclerView rvConsultation;
    @BindView(R.id.autoTurnViewPager)
    AutoTurnViewPager autoTurnViewPager;
    @BindView(R.id.defaultPageIndicator)
    DefaultPageIndicator defaultPageIndicator;
    private SimpleMF marqueeFactory;
    private boolean isUpdate;
    private HotActivityListAdapter hotactivitylistadapter;
    // 再点一次退出程序时间设置
    private static final long WAIT_TIME = 2000L;
    private long TOUCH_TIME = 0;

    public static ZhiXunFragment newInstance() {
        return new ZhiXunFragment();
    }

    @NonNull
    @Override
    public BasePresenter initPresenter() {
        return ZhiXunPresenter.newINstance();
    }

    @Override
    public void updateContentList(List<Object> list) {

    }

    @Override
    public void itemNotifyChanged(int position) {

    }

    /**
     * 获取到的banner数据
     *
     * @param homeBannerBean bannerbean'
     */
    @Override
    public void showHomeBannerDataSuccess(final HomeBannerBean homeBannerBean) {
        List<String> strings = new ArrayList<>();
        if (homeBannerBean != null && homeBannerBean.getData() != null && homeBannerBean.getData().size() > 0) {
            for (int i = 0; i < homeBannerBean.getData().size(); i++) {
                strings.add(Host.HostImg + homeBannerBean.getData().get(i).getImageUrl());
            }
        }

        autoTurnViewPager.setPages(BannerAdapter.holder)
                .setCanTurn(true)
                .setScrollDuration(2000);
        autoTurnViewPager.setPageTransformer(new ZoomOutPageTransformer());
//
        defaultPageIndicator.setPageIndicator(BannerAdapter.indicatorGrouop);
//
        UIContact.with(autoTurnViewPager, defaultPageIndicator)
                .setData(strings);


        autoTurnViewPager.setOnItemClickListener(new OnPageClickListener() {
            @Override
            public void onItemClick(int position) {
//                Toast.makeText(mActivity, "pos="+position, Toast.LENGTH_SHORT).show();
                if (homeBannerBean != null && homeBannerBean.getData() != null) {
                    Bundle bundle = new Bundle();
                    bundle.putString(Constants.BANNER_DETAIL, homeBannerBean.getData().get(position).getDetailInfo());
                    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
                        startNewActivity(TestDetailActivity.class, bundle);
                    } else {
                        startNewActivity(ZiXunDetailsActivity.class, bundle);
                    }
                }

            }
        });
    }

    @Override
    public void showNetworkError() {

    }

    /**
     * 获取首页公告数据成功
     *
     * @param homeNoticeBean homeNoticeBean'
     */
    @Override
    public void showHomeNoticeDataSuccess(HomeNoticeBean homeNoticeBean) {
        LogUtils.e("homeNoticeBean==" + homeNoticeBean.getData().get(0));
        marqueeFactory = new SimpleMF(getActivity());
        marqueeFactory.setData(homeNoticeBean.getData());
        smvNotice.setMarqueeFactory(marqueeFactory);
        smvNotice.startFlipping();
    }

    /**
     * 获取首页热门活动列表数据成功
     *
     * @param hostListBean listBean'
     */
    @Override
    public void showHomHotActivityListDataSuccess(final HostListBean hostListBean) {
//        if (hotactivitylistadapter.getData().size() == 0) {
        initRecycleView(hostListBean);
//        } else {
//            if (isUpdate) {//是下拉更新就替換當前數據
//                hotactivitylistadapter.setNewData(hostListBean.getData());
//            } else {
//                hotactivitylistadapter.addData(hostListBean.getData());
//            }
//        }
//        hotactivitylistadapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {//热门活动列表适配器監聽器
//            @Override
//            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
////                mPresenter.onItemClick(position, (ZhihuDailyItemBean) adapter.getItem(position));
//
//            }
//        });
        hotactivitylistadapter.setOnClickItem(new HotActivityListAdapter.onClickItem() {
            @Override
            public void clikPosition(int position) {
                Bundle bundle = new Bundle();
                bundle.putString(Constants.BANNER_DETAIL, hostListBean.getData().get(position).getDetailInfo());
                startNewActivity(ZiXunDetailsActivity.class, bundle);
            }
        });
        rvConsultation.setLoadingMoreEnabled(false);
        rvConsultation.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                hotactivitylistadapter.notifyDataSetChanged();
                LogUtil.e("adasdada");
                mPresenter.getHotActivityListData();//重新获取热门活动列表
            }

            @Override
            public void onLoadMore() {

            }
        });
//        ptrClass.refreshComplete();//
        rvConsultation.refreshComplete();
//        rvConsultation.refresh();
        hideProgressDialog();
//            rvConsultation.addOnItemTouchListener(new OnItemClickListener() {
//                @Override
//                public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
//
//                }
//            });
//            rvConsultation.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    Bundle bundle = new Bundle();
//                    bundle.putString(Constants.BANNER_DETAIL, hostListBean.getData().get(position).getDetailInfo());
//                    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
//                        startNewActivity(TestDetailActivity.class, bundle);
//                    } else {
//                        startNewActivity(ZiXunDetailsActivity.class, bundle);
//                    }
//                }
//            });
    }

    @Override
    public void showLoadMoreError() {

    }

    @Override
    public void showNoMoreData() {

    }

    @Override
    protected void onErrorViewClick(View view) {
        mPresenter.getHotActivityListData();//获取热门活动列表
    }

    @Override
    protected void showLoading() {
//        hotactivitylistadapter.setEmptyView(loadingView);
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_zixun;
    }

    @Override
    public void initUI(View view, @Nullable Bundle savedInstanceState) {

//        reFreshListener();//监听下拉
        //初始化一个空list的adapter，网络错误时使用，第一次加载到数据时重新初始化adapter并绑定recycleview


    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        mPresenter.getHomeBannerData();//获取banner
        mPresenter.getHomeNoticeData();//获取广告
        mPresenter.getHotActivityListData();//获取热门活动列表
    }

    @Override
    public void onPause() {
        super.onPause();
        smvNotice.stopFlipping();//暂停滚动
    }

    @Override
    public void onResume() {
        super.onResume();
        smvNotice.startFlipping();//开始滚动
        hideProgressDialog();
    }

    @Override
    public boolean onBackPressedSupport() {
        if (System.currentTimeMillis() - TOUCH_TIME < WAIT_TIME) {
//            mActivity.setIsTransAnim(false);
            mActivity.finish();
        } else {
            TOUCH_TIME = System.currentTimeMillis();
//                ToastUtils.showToast(R.string.press_again);
            ToastUtils.showToast("再按一次退出");
        }
        return true;
    }

//    /**
//     * 下拉刷新監聽
//     */
//    private void reFreshListener() {
//        MaterialHeader header = new MaterialHeader(mActivity);
//        ptrClass.addPtrUIHandler(header);
//        ptrClass.setLastUpdateTimeRelateObject(this);//设置刷新支持时间
//        ptrClass.setResistance(1.7f);//设置下拉的阻尼系数，值越大感觉越难下拉
//        ptrClass.setDurationToCloseHeader(1000);//设置刷新完成，头部回弹时间，注意和前一个进行区别
//        ptrClass.setPullToRefresh(false);//设置下拉过程中执行刷新，我们一般设置为false
//        ptrClass.setKeepHeaderWhenRefresh(true);//设置刷新的时候是否保持头部
//        ptrClass.setPtrHandler(new PtrDefaultHandler() {               //下拉刷新
//            @Override
//            public void onRefreshBegin(PtrFrameLayout frame) {
//                //模拟联网，延迟更新数据
//                new Handler().postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        hotactivitylistadapter.notifyDataSetChanged();
//                        isUpdate = true;//標誌下拉
//                        mPresenter.getHotActivityListData();//重新获取热门活动列表
//                    }
//                }, 1000);
//            }
//        });
//    }

    /**
     * 填充热门活动列表适配器·
     *
     * @param list
     */
    private void initRecycleView(final HostListBean list) {
        hotactivitylistadapter = new HotActivityListAdapter(mContext, list.getData());
        rvConsultation.setLayoutManager(new LinearLayoutManager(mActivity));
//        mZhihuAdapter.setOnLoadMoreListener(this, rvZhihu);
        rvConsultation.setAdapter(hotactivitylistadapter);
//        rvConsultation.refreshComplete();


    }

}
